SSH Using Keys
This section will cover the configuration to setup SSH using public keys.
Table of Contents
- Overview
- Creating Keys
- Configuring the Server
- Configuring the Client
Overview
Using SSH with password authentication can introduce a weakness as passwords can be brute forced, especially if they are simple.
With public key authentication, we can create a key that can be used for authentication instead of using a password.
The guide works on both Linux and Windows with minimal differences. Do note that the directory path is slightly different for both Windows and Linux.
On Linux:
/home/<username>/.ssh
On Windows:
C:\Users\<username>\.ssh
OR
%USERPROFILE%\.ssh
Creating Keys
To create the keys, use the ssh-keygen command on either Windows or Linux. To specify the number of bits to use, we can use the -b option.
ssh-keygen -b 4096

Once created, we can add the contents of the public key (id_rsa.pub if using default settings) to the remote server. The contents should be saved to a file called .ssh/authorized_keys in the user home directory. If the file does not exist, we can create it.
mkdir .ssh
touch .ssh/authorized_keys

Configuring the Server
Once the key has been added, we can disable password login by changing the PasswordAuthentication in the /etc/ssh/sshd_config file.
PasswordAuthentication no

Once done, restart the SSH service.
systemctl restart ssh
Configuring the Client
To make it easier to SSH to different machines, we can create a file called config in the .ssh directory. We can specify an alias with the required information for login.
Host <alias name>
Hostname <Target IP>
Port <port>
User <username>
IdentityFile "</path/to/id_rsa>"
Breakdown:
<alias name>- Specify the name to use. Can be anything.Port <port>- Specify the port to use for SSH on the target.User <username>- Specify the username to use for SSH.<IdentityFile "</path/to/id_rsa>"- Specify the path to theid_rsafile to use for authentication.
An example:
Host myserver
Hostname 10.10.10.1
Port 22
User myadmin
IdentityFile "/home/myuser/.ssh/id_rsa"
To SSH, we can type ssh <alias> instead of the usual <ssh <username>@<Target IP>.
ssh myserver